package com.shicijiaoliu.controller;

import com.shicijiaoliu.pojo.User;
import com.shicijiaoliu.pojo.result;
import com.shicijiaoliu.service.Userservice;
import com.shicijiaoliu.utils.JWTUtil;
import com.shicijiaoliu.utils.MD5Utils;
import com.shicijiaoliu.utils.MailMsg;
import com.shicijiaoliu.utils.ThreadLocalUtils;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Validated
@CrossOrigin
public class Usercontroller {

    @Autowired
    private Userservice userservice;

    @PostMapping("/register")
    public result register(@Pattern(regexp = "^\\S{3,15}$") String username,
                           @Pattern(regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{5,20}$") String password,
                           @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$") String email,
                           @Pattern(regexp = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$") String phone,
                           @Pattern(regexp = "^\\S{1,15}$") String nickname){
        //查询用户6
        User u = userservice.findByName(username);
        if (u==null){
            //没有占用，注册用户
            email = email.replace('\'',' ');
            phone = phone.replace('\'',' ');
            userservice.register(username,password,email,phone,nickname,null);
            return result.success();
        }else {
            //已占用
            return result.error("用户名已被占用");
        }

    }

    @PostMapping("/login")
    public result<String> login( String username, String password){
        User u = userservice.findByName(username);
            if (u==null){
                //没有账号
                return result.error("账号错误");
            }else {
                //找到账号
                if (u.getPassword().equals(MD5Utils.string2MD5(password)) ){
                    Map<String,Object> claims = new HashMap<>();
                    claims.put("id",u.getId());
                    claims.put("username",u.getUsername());
                    claims.put("ruler",u.getRuler());
                    String jwt = JWTUtil.sign(claims);
                    return result.success(jwt);
                }else{
                    return result.error("密码错误");
                }
        }
        }


    @GetMapping("/userinfo")
    public result<User> userinfo(@RequestHeader(name="Authorization") String token){
        Map<String,Object> claims = ThreadLocalUtils.getThreadLocal();
        String username = String.valueOf(claims.get("username"));
        User u = userservice.findByName(username);
        return result.success(u);
    }


    @PutMapping("/update")
    public result update(String username,String nickname,String email,String phone,long id,String ruler,String sex,long age,String hobby){
        User u = new User(username,nickname,email,phone,id,ruler,sex,age,hobby);
        userservice.update(u);
        return result.success();
    }

    @PatchMapping("/updatepwd")
    public result updatepwd(String password,String newpassword,String checknewpwd){
        String oldpwd = password;
        String newpwd = newpassword;
        String qrpwd = checknewpwd;

        if(oldpwd.isEmpty() || newpwd.isEmpty() || qrpwd.isEmpty()){
            return result.error("参数缺少");
        }

        if(!newpwd.equals(qrpwd)){
            return result.error("两次密码不一致");
        }

        Map<String,Object> claims = ThreadLocalUtils.getThreadLocal();
        User u = userservice.findByName((String) claims.get("username"));
        if(MD5Utils.passwordIsTrue(oldpwd, u.getPassword())){
            userservice.updatepwd(newpwd);
            return result.success();
        }else return result.error("旧密码输入错误");

    }

    @PatchMapping("/findpwd")
    public result findpwd(String password,String rePassword,String email){
        String newpwd = password;
        String qrpwd = rePassword;

        if(newpwd.isEmpty()  || qrpwd.isEmpty()){
            return result.error("参数缺少");
        }

        if(!qrpwd.equals(newpwd)){
            return result.error("两次密码不一致");
        }
        userservice.findpwd(newpwd,email);
        return result.success();

    }


    @GetMapping("/checkpwd/{password}")
    public boolean delshici(@PathVariable("password")String password){
        Map<String,Object> claims = ThreadLocalUtils.getThreadLocal();
        User u = userservice.findByName((String) claims.get("username"));
        if(MD5Utils.passwordIsTrue(password,u.getPassword())){
            return true;
        }else {
            return false;
        }
    }

    @GetMapping("/sendemail/{email}")
    public result email(@PathVariable("email")String email){
        String code = MailMsg.mail(email);
        return result.success(code);
    }

    @PostMapping("/uploadimg")
    public String uploadimg(@RequestParam("file")MultipartFile mFile,@RequestHeader(name="id") long id) throws IOException {
        if(mFile != null){
        // 定义存储图片的地址
        String folder = "D:/item/biyesheji/shici/shicivue/src/images";
        // 文件夹
        File imgFolder = new File(folder);
        // 获取文件名
        String fname = mFile.getOriginalFilename();
        // 获取文件后缀
        String ext = "." + fname.substring(fname.lastIndexOf(".")+1);
        // 获取时间字符串
        String dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
        // 生成新的文件名
        String newFileName = dateTimeFormatter + UUID.randomUUID().toString().replaceAll("-","") + ext;
        // 文件在本机的全路径
        File filePath = new File(imgFolder, newFileName);
        String src = filePath.getName();
        mFile.transferTo(filePath);
        userservice.updateimg(src,id);
        return filePath.getName();
        }
        else return "";
    }


}
